﻿using System;
using System.IO;
using System.Windows.Forms;
using SmartMotion.Core.Mgrs;

namespace SmartMotion.Core
{
    public class ProductMgr
    {
        #region 单例

        private static readonly Lazy<ProductMgr> Instance = new Lazy<ProductMgr>(() => new ProductMgr());

        private ProductMgr()
        {
        }

        public static ProductMgr Ins { get; } = Instance.Value;

        #endregion 单例

        public string FilePath { get; set; } = string.Empty;

        #region 产品管理

        public void New()
        {
            VarMgr.Ins.Vars[VarMgr.ProductPars].Clear();
        }

        public void Open()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "产品文件（*.xml）| *.xml";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() != DialogResult.OK) return;
            FilePath = openFileDialog.FileName;

            Open(FilePath);
        }

        public void Open(string file)
        {
            //if (File.Exists(file))
            {
                FilePath = file;
                VarMgr.Ins.LoadDic(VarMgr.ProductPars, FilePath, false);
                PointsMgr.Ins.Open();
            }
        }

        public void Save()
        {
            if (!File.Exists(FilePath))
            {
                SaveAs();
            }
            VarMgr.Ins.SaveDic(VarMgr.ProductPars, FilePath);
            string path = Path.GetFullPath(FilePath);
            if (!Directory.Exists(path.Replace(".xml","\\")))
            {
                Directory.CreateDirectory(path);
            }
            PointsMgr.Ins.Save();
        }

        public void SaveAs()
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "产品文件（*.xml）| *.xml";
            sfd.FilterIndex = 1;
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog()==DialogResult.OK)
            {
                FilePath = sfd.FileName;
            }
        }

        #endregion 产品管理
    }
}
